<template>
  <div class="training-detail-page">
    <!-- 标签页导航 -->
    <el-tabs v-model="activeTab" class="custom-tabs">
      <!-- 培训班详情 -->
      <el-tab-pane label="培训班详情" name="detail">
        <div class="tab-content">
          <!-- 班级基本信息 -->
          <div class="section">
            <h3 class="section-title">班级基本信息</h3>
            <el-table :data="[basicInfo]" border style="width: 100%">
              <el-table-column
                prop="signUpCategory"
                label="报名类别"
                :formatter="formatSignUpCategory"
              />
              <el-table-column prop="trainingProjectNames" label="报名项目" />
              <el-table-column prop="trainingClassCode" label="培训班编号" />
              <el-table-column prop="trainingClassName" label="培训班名称" />
              <el-table-column prop="trainingYear" label="年份" />
              <el-table-column prop="trainingSession" label="期次" />
              <el-table-column
                prop="startupType"
                label="开班类型"
                :formatter="formatStartupType"
              />
              <el-table-column
                prop="trainingType"
                label="培训类别"
                :formatter="formatTrainingType"
              />
              <el-table-column prop="trainingDepartmentName" label="培训部门" />
              <el-table-column prop="startDate" label="培训开始日期" />
              <el-table-column prop="endDate" label="培训截止日期" />
              <el-table-column prop="trainingRegion" label="培训地区" />
              <el-table-column prop="trainingAddress" label="培训地址" />
              <el-table-column prop="trainingVenue" label="培训地点" />
              <el-table-column prop="actualTrainingVenue" label="实际培训地点" />
              <el-table-column prop="headTeacher1Name" label="班主任1" />
              <el-table-column prop="headTeacher2Name" label="班主任2" />
            </el-table>
          </div>

          <!-- 培训课程 -->
          <div class="section">
            <h3 class="section-title">培训课程</h3>
            <el-table :data="courses" border style="width: 100%">
              <el-table-column prop="courseName" label="课程名称" />
              <el-table-column
                prop="courseType"
                label="课程类型"
                :formatter="formatCourseType"
              />
              <el-table-column prop="hours" label="学时" />
            </el-table>
          </div>

          <!-- 培训教师 -->
          <div class="section">
            <h3 class="section-title">培训教师</h3>
            <el-table :data="teachers" border style="width: 100%">
              <el-table-column prop="courseName" label="课程名称" />
              <el-table-column prop="teacherName" label="教师姓名" />
              <el-table-column prop="deptName" label="所属部门" />
            </el-table>
          </div>

          <!-- 培训教材 -->
          <div class="section">
            <h3 class="section-title">培训教材</h3>
            <el-table :data="textbooks" border style="width: 100%">
              <el-table-column prop="bookName" label="教材名称" />
              <el-table-column prop="publisher" label="出版社" />
              <el-table-column prop="isbn" label="ISBN" />
              <el-table-column prop="pubTime" label="出版时间" />
              <el-table-column prop="price" label="单价" :formatter="formatPrice" />
            </el-table>
          </div>

          <!-- 培训证书 -->
          <div class="section">
            <h3 class="section-title">培训证书</h3>
            <el-table :data="certificates" border style="width: 100%">
              <el-table-column prop="certName" label="证书名称" />
              <el-table-column prop="certType" label="证书类型" />
              <el-table-column
                prop="isIssued"
                label="是否发放"
                :formatter="formatIsIssued"
              />
            </el-table>
          </div>
        </div>
      </el-tab-pane>

      <!-- 培训计划 -->
      <el-tab-pane label="培训计划" name="plan">
        <div class="tab-content">
          <el-table :data="trainingPlan" border style="width: 100%">
            <el-table-column prop="content" label="培训内容" />
            <el-table-column prop="planTime" label="培训时间" />
            <el-table-column prop="location" label="培训地点" />
            <el-table-column prop="teacherName" label="培训教师" />
            <el-table-column prop="scheduleRemarks" label="备注" />
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 培训资料 -->
      <el-tab-pane label="培训资料" name="material">
        <div class="tab-content">
          <el-button type="primary" class="download-btn" @click="downloadMaterial">
            下载培训资料
          </el-button>
          <el-table :data="materials" border style="width: 100%; margin-top: 16px;">
            <el-table-column prop="fileName" label="资料名称" />
            <el-table-column prop="fileSize" label="文件大小(KB)" :formatter="formatFileSize" />
            <el-table-column prop="uploadTime" label="上传时间" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="downloadFile(scope.row.fileUrl)"
                >
                  下载
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 考试安排（已适配新数据结构） -->
      <el-tab-pane label="考试安排" name="exam">
        <div class="tab-content">
          <el-table :data="examArrangement" border style="width: 100%">
            <!-- <el-table-column prop="paperConfigName" label="考试名称" /> -->
            <el-table-column prop="examStartTime" label="考试开始时间" />
            <el-table-column prop="examEndTime" label="考试结束时间" />
            <el-table-column prop="examDuration" label="考试时长（分钟）" />
            <el-table-column prop="examLocation" label="考试地址" />
            <el-table-column
              prop="examPathway"
              label="考试途径"
            />
            <el-table-column
              prop="examPassScore"
              label="考试通过分数"
              :formatter="formatScore"
            />
            <el-table-column
              prop="ifReleaseResultsImmediately"
              label="是否即时发布成绩"
              :formatter="formatReleaseImmediately"
            />
            <el-table-column
              prop="ifAgreeAutomaticExam"
              label="是否允许补考"
              :formatter="formatAllowMakeup"
            />
            <el-table-column prop="examTimes" label="可补考次数" />
            <el-table-column prop="resultsAnnouncementTime" label="成绩发布时间" />
            <!-- <el-table-column prop="invigilatorId" label="监考人员" /> -->
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 通知推送 -->
      <el-tab-pane label="通知推送" name="notice">
        <div class="tab-content">
          <el-table :data="notices" border style="width: 100%">
            <el-table-column prop="sendTime" label="通知时间" />
            <el-table-column label="通知渠道"><span>门户</span>
              <!-- <template slot="scope">
                <span>门户</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="noticeContent" label="通知内容" />
            <el-table-column prop="createBy" label="发布人" />
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
// 导入所有必要接口
import {
  trainingClassList,
  listCourses,
  listTeachers,
  listTextbooks,
  listCertificates,
  listTrainingPlans,
  listMaterials,
  downloadFile
} from "@/api/training/TrainingClass";
import { listByStudentIdAndClassId } from "@/api/training/noticeReceive";
import { listByClassId, batchUpdateByClass, } from "@/api/training/TrainingSchedule";
import { getByClassId } from "@/api/training/examSchedule";
import { getUser } from "@/api/system/user";
import { getExamScheduleByStudentId } from "@/api/training/ClassStudent";

export default {
  name: 'TrainingDetailPage',
  props: {
    classId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      activeTab: 'detail',
      // 所有数据容器
      basicInfo: {},
      courses: [],
      teachers: [],
      textbooks: [],
      certificates: [],
      trainingPlan: [],
      examArrangement: [], // 适配新考试安排数据结构
      notices: [],
      materials: []
    }
  },
  watch: {
    classId: {
      immediate: true,
      handler() {
        this.loadTrainingDetail()
      }
    }
  },
  methods: {
    // 加载所有详情数据
    async loadTrainingDetail() {
      try {
        // 1. 加载班级基本信息
        const classRes = await trainingClassList({ trainingClassId: this.classId })
        this.basicInfo = classRes.rows[0] || {}

        // // 2. 加载课程列表
        // const courseRes = await listCourses({ trainingClassId: this.classId })
        // this.courses = courseRes.rows || []

        // // 3. 加载教师列表
        // const teacherRes = await listTeachers({ trainingClassId: this.classId })
        // this.teachers = teacherRes.rows || []

        // // 4. 加载教材列表
        // const textbookRes = await listTextbooks({ trainingClassId: this.classId })
        // this.textbooks = textbookRes.rows || []

        // // 5. 加载证书列表
        // const certRes = await listCertificates({ trainingClassId: this.classId })
        // this.certificates = certRes.rows || []

        // 6. 加载培训计划（修复教师姓名为Promise的问题）
        const planRes = await listByClassId(this.classId);
        const planRows = planRes.rows || [];

        // 1. 提取所有不重复的教师ID
        const teacherIds = [...new Set(planRows.map(row => row.scheduleTeacherId).filter(Boolean))];

        // 2. 批量获取教师信息（优化：减少重复请求）
        const teacherMap = {};
        if (teacherIds.length > 0) {
          // 若后端支持批量查询，可替换为批量接口（更高效）
          for (const id of teacherIds) {
            try {
              const res = await getUser(id);
              teacherMap[id] = res.data?.nickName || '未知教师';
            } catch (error) {
              console.error(`获取教师${id}信息失败`, error);
              teacherMap[id] = '获取失败';
            }
          }
        }

        // 3. 处理培训计划数据（使用预加载的教师映射表）
        this.trainingPlan = planRows.map(row => ({
          content: row.trainingContent || '-',
          planTime: row.scheduleStartTime && row.scheduleEndTime
            ? `${row.scheduleStartTime} 至 ${row.scheduleEndTime}`
            : (row.scheduleStartTime || row.scheduleEndTime || '-'),
          location: row.scheduleAddress || '-',
          // 从映射表中获取教师姓名，避免Promise
          teacherName: teacherMap[row.scheduleTeacherId] || '-',
          scheduleRemarks: row.scheduleRemarks || '-'
        }));

        // 7. 加载考试安排（适配新数据结构）
        const examRes = await getExamScheduleByStudentId(this.classId,this.$store.state.user.studentId)
        this.examArrangement = examRes.rows || []

        // 8. 加载通知列表
        console.log(this.$store.state.user)
        const noticeRes = await listByStudentIdAndClassId({trainingClassId:this.classId,studentId:this.$store.state.user.studentId})
        this.notices = noticeRes.rows || []

        // // 9. 加载培训资料
        // const materialRes = await listMaterials({ trainingClassId: this.classId })
        // this.materials = materialRes.rows || []

      } catch (error) {
        console.error('加载培训班详情失败：', error)
        this.$message.error('加载详情失败，请重试')
      }
    },
    async getUser(userId){
      const res =await getUser(userId);
      return res.data.nickName
    },

    // 格式化：报名类别
    formatSignUpCategory(row) {
      const map = {
        'regular': '常规报名',
        'recommend': '推荐报名',
        'internal': '内部报名',
        'system': '系统报名'
      }
      return map[row.signUpCategory] || row.signUpCategory || '-'
    },

    // 格式化：开班类型
    formatStartupType(row) {
      const map = {
        '1': '线下集中',
        '2': '线上线下结合',
        '3': '线下实践',
        '4': '纯线上'
      }
      return map[row.startupType] || row.startupType || '-'
    },

    // 格式化：培训类别
    formatTrainingType(row) {
      const map = {
        '1': '在职培训',
        '2': '专业培训',
        '3': '进阶培训',
        '4': '岗前培训'
      }
      return map[row.trainingType] || row.trainingType || '-'
    },

    // 格式化：课程类型
    formatCourseType(row) {
      const map = {
        '1': '线上',
        '2': '线下',
        '3': '实践'
      }
      return map[row.courseType] || row.courseType || '-'
    },

    // 格式化：是否发放（证书）
    formatIsIssued(row) {
      const map = {
        '0': '未发放',
        '1': '已发放',
        '2': '发放中'
      }
      return map[row.isIssued] || row.isIssued || '-'
    },

    // 格式化：考试途径（适配0-手机、1-电脑，支持多选拼接）
    formatExamWay(row) {
      if (!row.examPathway) return '-'
      const map = {
        '0': '手机',
        '1': '电脑'
      }
      // 处理多选拼接场景（如"0,1" -> "手机,电脑"）
      return row.examPathway.split(',').map(key => map[key] || key).join(',')
    },

    // 格式化：是否即时发布成绩（0-是，1-否）
    formatReleaseImmediately(value) {
      const map = {
        '0': '是',
        '1': '否',
        null: '-',
        undefined: '-'
      }
      return map[value.ifReleaseResultsImmediately] || value.ifReleaseResultsImmediately || '-'
    },

    // 格式化：是否允许补考（0-是，1-否）
    formatAllowMakeup(value) {
      const map = {
        '0': '是',
        '1': '否',
        null: '-',
        undefined: '-'
      }
      return map[value.ifAgreeAutomaticExam] || value.ifAgreeAutomaticExam || '-'
    },

    // 格式化：分数
    formatScore(score) {
      return score.examPassScore !== null && score.examPassScore !== undefined ? `${score.examPassScore}分` : '-'
    },

    // 格式化：价格
    formatPrice(price) {
      return price !== null && price !== undefined ? `¥${price}` : '-'
    },

    // 格式化：文件大小
    formatFileSize(size) {
      return size !== null && size !== undefined ? `${size} KB` : '-'
    },

    // 下载全部资料
    downloadMaterial() {
      if (this.materials.length === 0) {
        this.$message.warning('暂无培训资料可下载')
        return
      }
      // 实际项目中调用批量下载接口
      this.$message.success('开始下载全部资料')
    },

    // 下载单个文件
    async downloadFile(fileUrl) {
      if (!fileUrl) {
        this.$message.warning('文件地址不存在')
        return
      }
      try {
        await downloadFile({ fileUrl })
        this.$message.success('文件下载中')
      } catch (error) {
        this.$message.error('下载失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.training-detail-page {
  padding: 16px 0;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

/* 标签页样式 */
.custom-tabs {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
  margin: 0 16px;
}

/* 覆盖Element UI标签页样式 */
::v-deep .el-tabs__header {
  margin-bottom: 20px;
}

::v-deep .el-tabs__item {
  font-size: 14px;
  color: #6b7280;
  padding: 0 16px;
}

::v-deep .el-tabs__item.is-active {
  color: #165dff;
  font-weight: 500;
}

::v-deep .el-tabs__active-bar {
  background-color: #165dff;
  height: 2px;
}

/* 标签内容区 */
.tab-content {
  padding: 8px 0;
}

/* 板块标题 */
.section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1f2329;
  margin-bottom: 12px;
  padding-bottom: 6px;
  border-bottom: 1px solid #e8e8e8;
}

/* 下载按钮 */
.download-btn {
  padding: 8px 24px;
  font-size: 14px;
  margin-bottom: 16px;
}

/* 表格样式优化 */
::v-deep .el-table {
  margin-bottom: 16px;
  font-size: 13px;
}

::v-deep .el-table th {
  background-color: #f9fafb;
  font-weight: 500;
  padding: 10px 0;
}

::v-deep .el-table td {
  vertical-align: middle;
  padding: 10px 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .class-info {
    margin-right: 20px;
    font-size: 13px;
  }

  .section-title {
    font-size: 14px;
  }
}
</style>
